package com.scy.jdbc;

import com.scy.jdbc.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//使用jdbc实现更新和删除
public class JDBCCommon {
    public static void main(String[] args) {
//        new JDBCCommon().updateAccount();
        new JDBCCommon().deleteAccount();
    }
    //删除数据
    public int deleteAccount(){
        Connection conn = null;
        PreparedStatement ps =null;
        int rows = 0;
        try {
            //获取连接通过工具类完成注册驱动和获取链接
            conn = JDBCUtil.getConn();
            //定义sql
            String sql = "delete from account where id = ?";
            //获取执行sql的传输器对象
            ps = conn.prepareStatement(sql);
            //设置栈内存的值
            ps.setInt(1,4);
            //执行sql
            rows = ps.executeUpdate();
            //处理结果集
            if (rows > 0){
                System.out.println("删除成功，影响了"+rows+"行记录");
            }else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.closeIO(ps);
            JDBCUtil.closeIO(conn);
        }
        return 0;
    }
    //更新数据
    public int updateAccount(){
        Connection conn = null;
        int rows = 0;
        PreparedStatement ps = null;
        try {
            //获取连接通过工具类完成注册驱动和获取链接
            conn = JDBCUtil.getConn();
            //定义sql
            String sql =
                    "update account set name = ?,money = ? where id = ?";
            //获取执行sql的传输器对象
            ps = conn.prepareStatement(sql);
            //设置栈内存的值
            ps.setString(1,"app");
            ps.setDouble(2,1000000);
            ps.setInt(3,4);
            //执行sql
            rows = ps.executeUpdate();
            //处理结果集
            if (rows > 0){
                System.out.println("更新成功，影响了"+rows+"行记录");
            }else {
                System.out.println("更新失败");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //释放资源
            JDBCUtil.closeIO(ps);
            JDBCUtil.closeIO(conn);
            //关闭资源
//            if (ps!=null) {
//                try {
//                    ps.close();
//                } catch (SQLException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//            if (conn!=null) {
//                try {
//                    conn.close();
//                } catch (SQLException e) {
//                    throw new RuntimeException(e);
//                }
//            }
        }

        return rows;
    }
}
